package cn.com.chec.en.controller.front;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.chec.en.dao.NewsInfoDao;
import cn.com.chec.en.model.domain.NewsInfo;
import cn.com.chec.en.util.TimeUtils;

import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;

@Controller
public class RSSFrontController {
	protected static final Logger logger = Logger
			.getLogger(RSSFrontController.class);

	@Resource
	private NewsInfoDao newsInfoDao;

	@RequestMapping(value = { "/rss" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
	public void rss(HttpServletRequest request, HttpServletResponse response,
			ModelMap map) throws IOException, FeedException {
		String basePath = request.getScheme() + "://" + request.getServerName()
				+ ":" + request.getServerPort() + request.getContextPath()
				+ "/";
		response.setContentType("text/xml; charset=UTF-8");

		SyndFeed feed = new SyndFeedImpl();
		feed.setFeedType("rss_2.0");
		feed.setTitle("CHINA  HUADIAN ENGINEERING CO., LTD. NEWS");
		feed.setLink(basePath + "news");
		feed.setDescription("CHINA  HUADIAN ENGINEERING CO., LTD. NEWS");

		List<SyndEntry> entries = new ArrayList<SyndEntry>();
		SyndEntry entry = null;
		SyndContent content = null;
		List<NewsInfo> newsInfoList = this.newsInfoDao.rss(1, 0, 30);
		for (NewsInfo newsInfo : newsInfoList) {
			entry = new SyndEntryImpl();
			entry.setTitle(newsInfo.getTitle());
			entry.setLink(basePath + "news/" + newsInfo.getNewsId());
			entry.setAuthor("CHINA  HUADIAN ENGINEERING");
			entry.setPublishedDate(TimeUtils.formatDate(newsInfo
					.getPublishTime()));

			content = new SyndContentImpl();
			content.setType("text/plain");
			content.setValue(newsInfo.getContent());
			entry.setDescription(content);

			entries.add(entry);
		}
		feed.setEntries(entries);
		SyndFeedOutput output = new SyndFeedOutput();
		output.output(feed, response.getWriter());
	}
}